<?php
//通用函数 willson 2014/9/3

//实例化一个模型类
function m($model) {
	$file = MODEL_PATH . "/{$model}.model.php";
	if (file_exists($file)) {
		include_once($file);
		$class = $model."_model";
		$model = new $class;
		return $model;
	} else {
		error("Missing model file");
	}
}

//实例化一个类
function cc($app, $path='api') {
	$file = PROTECTED_PATH . "/{$path}/{$app}.php";
	if (file_exists($file)) {
		include_once($file);
		if (class_exists($app)) {
			$class = new $app();
			return $class;
		} else {
			error('Missing controller');
		}
	} else {
		error("Missing controller file");
	}
}

//根据表字段实例化一个字典类
function t($table) {
	global $db, $tbp;
	$desc = $db->get_results("DESC {$tbp}{$table}");
	$class = new stdClass();
	foreach ($desc as $g) {
		if (preg_match("/^(char|varchar|text|tinytext|mediumtext|longtext)/i", $g->Type)) {
			$class->{$g->Field} = $g->Default ? $g->Default : '';
		} else if ($g->Field=='id') {
			$class->{$g->Field} = 0;
		} else {
			if (preg_match("/^(float|decimal|double)/i", $g->Type)) {
				$class->{$g->Field} = $g->Default ? floatval($g->Default) : 0;
			} else {
				$class->{$g->Field} = $g->Default ? intval($g->Default) : 0;
			}
		}
	}
	return $class;
}

function object2array($obj) {
	$arr = array();
	if (is_object($obj)) {
		foreach ($obj as $k=>$v) {
			$arr[$k] = $v;
		}
		return $arr;
	}
	return $obj;
}

//将一个activeobject对象格式化输出
function ar2object($active_record_obj) {
	if (is_object($active_record_obj)) {
		$obj = new stdClass();
		$attributes = $active_record_obj->attributes();
		foreach ($attributes as $k=>$attr) {
			$obj->$k = $attr;
		}
		return $obj;
	}
	return $active_record_obj;
}

//将一个activeobject对象输出成数组
function ar2array($active_record_obj) {
	if (is_object($active_record_obj)) {
		if (method_exists($active_record_obj, 'to_array')) {
			$arr = $active_record_obj->to_array();
			//将数字也格式化成字符串输出成json
			if (is_array($arr) && count($arr)) {
				foreach ($arr as $k=>$v) {
					if (is_numeric($v)) {
						$arr[$k] = strval($v);
					}
				}
			}
			return $arr;
		}
	}
	return $active_record_obj;
}

//将一个包含有relationship的AR对象的数组输出成数组
function ars2array($active_record_array, $relationships=array()) {
	if (is_array($active_record_array) && count($active_record_array)) {
		$array = array();
		$results = array();
		foreach ($active_record_array as $k=>$obj) {
			if ($relationships) {
				foreach ($relationships as $name) {
					//if (method_exists($obj, $name)) {
					$results[$name] = array_map("ar2array", $obj->$name);
					//}
				}
			}
			$obj = ar2array($obj);
			if ($results) {
				foreach ($results as $k=>$v) {
					$obj[$k] = $v;
				}
			}
			$array[] = $obj;
		}
		return $array;
	} else {
		return $active_record_array;
	}
}

//upload_upyun:上传到又拍云，return_array:返回文件所有信息(数组), force_img:强制图片
//上传文件,自动判断name是否数组形式
function upload_file($mydir, $field, $upload_upyun=true, $return_array=false, $force_img=true) {
	if (!isset($_FILES[$field])) exit('FILE ERROR');
	if (is_array($_FILES[$field]['name'])) {
		return upload_one_file($mydir, $field, $upload_upyun, $return_array, $force_img);
	} else {
		return upload_array_file($mydir, $field, $upload_upyun, $return_array, $force_img);
	}
}

//上传单个文件
function upload_one_file($mydir, $field, $upload_upyun=true, $return_array=false, $force_img=true) {
	$file = upload_obj_file($_FILES, $mydir, $field, $upload_upyun, $return_array, $force_img);
	if (!$file || (is_array($file) && !count($file))) $file = isset($_POST["origin_{$field}"]) ? trim($_POST["origin_{$field}"]) : '';
	return $file;
}

//上传数组形式文件
//20151211 by ajsong 为了兼容数组形式的file, e.g.: name="pic[]"
function upload_array_file($mydir, $field, $upload_upyun=true, $return_array=false, $force_img=true) {
	if (!isset($_FILES[$field])) return array();
	$file = $_FILES[$field];
	$name = $file['name'];
	$type = $file['type'];
	$tmp_name = $file['tmp_name'];
	$error = $file['error'];
	$size = $file['size'];
	$files = array();
	for ($i=0; $i<count($name); $i++) {
		if ($name[$i] != '') {
			$fileObj = array();
			$fileObj[$field] = array();
			$fileObj[$field]['name'] = $name[$i];
			$fileObj[$field]['type'] = $type[$i];
			$fileObj[$field]['tmp_name'] = $tmp_name[$i];
			$fileObj[$field]['error'] = $error[$i];
			$fileObj[$field]['size'] = $size[$i];
			$files[] = upload_obj_file($fileObj, $mydir, $field, $upload_upyun, $return_array, $force_img);
		} else {
			$files[] = $return_array ? array() : '';
		}
	}
	return $files;
}

//上传多个文件, e.g.:name="pic1", name="pic2", name="pic3"
function upload_files($mydir, $field, $num=3, $upload_upyun=true, $return_array=false, $force_img=true) {
	$files = array();
	for ($i=1; $i<=$num; $i++) {
		$files[] = upload_one_file($mydir, $field.$i, $upload_upyun, $return_array, $force_img);
	}
	return $files;
}

//上传文件操作
function upload_obj_file($fileObj, $mydir, $field, $upload_upyun=true, $return_array=false, $force_img=true) {
	global $upyun_bucketname, $upyun_operator_name, $upyun_operator_pwd, $upyun_domain;
	$file_array = array('file'=>'', 'type'=>'');
	if ( isset($fileObj[$field]) && (is_string($fileObj[$field]) || (is_array($fileObj[$field]) && $fileObj[$field]['size']>0)) ) {
        if ($force_img && is_array($fileObj[$field]) && isset($fileObj[$field]['type']) && stripos($fileObj[$field]['type'],'image/')===false) {
            $html = "<meta charset='UTF-8' /><script>alert('请上传图片');history.back();</script>";
            exit($html);
        }
		$file = '';
		$dir = UPLOAD_PATH ."/{$mydir}/".date('Y').'/'.date('m').'/'.date('d');
		$filename = (is_array($fileObj[$field]) && isset($fileObj[$field]['name'])) ? $fileObj[$field]['name'] : date("Ymd").rand(10000,99999).'.jpg';
		$names = explode('.', $filename);
		$ext = $names[count($names)-1];
		$file_array['type'] = $ext;
		if (is_array($fileObj[$field]) && isset($fileObj[$field]['size'])) $file_array['size'] = $fileObj[$field]['size'];
		$name = generate_order_sn();
		//上传到又拍云
        if ($upload_upyun) {
			include_once(FRAMEWORK_PATH."/class/upyun/upyun.class.php");
			if (is_array($fileObj[$field]) && isset($fileObj[$field]['type']) && stripos($fileObj[$field]['type'],'image/')!==false) {
				$size = getimagesize($fileObj[$field]['tmp_name']);
				$file_array['width'] = $size[0];
				$file_array['height'] = $size[1];
			}
			$file = $dir.'/'.$name.'.'.$ext;
            $upyun = new UpYun($upyun_bucketname, $upyun_operator_name, $upyun_operator_pwd);
            try {
				if (is_array($fileObj[$field]) && isset($fileObj[$field]['tmp_name'])) {
					$local_file = $fileObj[$field]['tmp_name'];
					$fh = fopen($local_file, 'rb');
					$upyun->writeFile($file, $fh, true); //上传图片，自动创建目录
					fclose($fh);
				} else {
					$upyun->writeFile($file, $fileObj[$field], true);
				}
                $file = $upyun_domain . $file;
            }
            catch (Exception $e) {
                $file = $file;
            }
        } else {
			$upload_dir = ROOT_PATH . $dir;
			if (!is_dir($upload_dir)) makedir($upload_dir);
			if (is_array($fileObj[$field])) {
				include_once(FRAMEWORK_PATH."/class/upload/class.upload.php");
				$upload = new Upload($fileObj[$field]);
				if ($upload->uploaded) {
					$upload->file_new_name_body = $name;
					$upload->Process($upload_dir);
					if ($upload->processed) {
						if (stripos($fileObj[$field]['type'],'image/')!==false) {
							$file_array['width'] = $upload->image_src_x;
							$file_array['height'] = $upload->image_src_y;
						}
						$file = $dir.'/'.$upload->file_dst_name;
					}
				}
				$upload->Clean();
			} else {
				$savename = $name.'.'.$ext;
				$pathname = $upload_dir.'/'.$savename;
				$handle = @fopen($pathname, 'w') or error('Unable to write file!');
				@fwrite($handle, $fileObj[$field]);
				@fclose($handle);
				$file = $dir.'/'.$savename;
			}
		}
		$file_array['file'] = $file;
	} else if (isset($_POST[$field])) {
		//20150629 by ajsong 修复如果不是文件即以POST形式获取
		$file = $_POST[$field];
		$file_array['file'] = $file;
	}
	//print_r($file_array);
	if ($return_array) {
		return $file_array;
	} else {
		return $file_array['file'];
	}
}

//下载远程文件到本地
function download_file($dir, $urls) {
	$dir = str_replace(ROOT_PATH, '', $dir);
	$paths = array();
	foreach ($urls as $url) {
		if (!strlen($url)) continue;
		$file = file_get_contents($url);
		$filename = pathinfo($url, PATHINFO_BASENAME);
		$res = fopen(ROOT_PATH.$dir.'/'.$filename, 'a');
		fwrite($res, $file);
		fclose($res);
		$paths[] = $dir.'/'.$filename;
	}
	return $paths;
}

//生成订单序列号
function generate_order_sn() {
	return date("ynjGis").rand(10000, 99999);
}

//生成sign
function generate_sign() {
	return md5(md5(rand(100000,999999)).time());
}

//生成密码盐值salt
function generate_salt() {
	$salt = rand(100000, 999999);
	return $salt;
}

//根据盐值生成加密密码
function crypt_password($password, $salt) {
	return md5(md5($password).$salt);
}

//导出成excel
function export_excel2($rs, $fields, $file_name='') {
    require_once FRAMEWORK_PATH . '/class/PHPExcel_1.8.0/Classes/PHPExcel.php';
	$objPHPExcel = new PHPExcel();
	//表格头
	$column = 'A';
	$row_number = 1;
	foreach ($fields as $k => $field) {
		$cell = "{$column}{$row_number}";
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue("{$cell}", $field);
		$objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getStyle($cell)->applyFromArray(
			array(
				'font' => array (
					'bold' => true
				),
				'alignment' => array(
					'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
				)
			)
		);
		$column ++;
	}
	$row_number = 2; // 1-based index
	foreach ($rs as $k => $order) {
		$column = 'A';
		$objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
		foreach ($fields as $field=>$name) {
			if (array_key_exists($field, $fields)) {
				$cell = $column . $row_number;
				$objPHPExcel->getActiveSheet()->setCellValue($cell, "{$order->$field}");
				$objPHPExcel->getActiveSheet()->getStyle($cell)->applyFromArray(
					array(
						'alignment' => array(
							'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
							'wrap' => true,
						)
					)
				);
				$column ++;
			}
		}
		$row_number ++;
	}
	// Redirect output to a client’s web browser (Excel2007)
	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	header('Content-Disposition: attachment;filename="'.$file_name.time().'.xlsx"');
	header('Cache-Control: max-age=0');
	// If you're serving to IE 9, then the following may be needed
	header('Cache-Control: max-age=1');
	// If you're serving to IE over SSL, then the following may be needed
	header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	header ('Pragma: public'); // HTTP/1.0
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	$objWriter->save('php://output');
	exit;
}

//导出成excel，$return为true即在服务器生成文件，$fields = array('id'=>'ID', 'name'=>'姓名', 'mobile'=>'电话');
function export_excel($rs, $fields, $return=false) {
	$objPHPExcel = new PHPExcel();
	//表格头
	$column = 'A';
	$row_number = 1;
	foreach ($fields as $field=>$name) {
		$cell = "{$column}{$row_number}";
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue("{$cell}", "{$name} ");
		$objSheet = $objPHPExcel->getActiveSheet();
		$objSheet->getColumnDimension($column)->setAutoSize(true);
		$objSheet->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
			->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
		$objSheet->getStyle("{$cell}")->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
		$objSheet->getStyle("{$cell}")->getAlignment()->setWrapText(false);
		$column++;
	}
	$row_number = 2; //1:based index
	foreach ($rs as $k=>$g) {
		$column = 'A';
		foreach ($fields as $field=>$name) {
			$cell = "{$column}{$row_number}";
			$objSheet = $objPHPExcel->getActiveSheet();
			$objSheet->getColumnDimension($column)->setAutoSize(true);
			if (array_key_exists($field, $g)) {
 				if (is_numeric($g->$field)) {
					$objSheet->setCellValue("{$cell}", " {$g->$field}", PHPExcel_Cell_DataType::TYPE_STRING);
				} else {
					$objSheet->setCellValue("{$cell}", "{$g->$field}");
				}
			} else {
				$objSheet->setCellValue("{$cell}", "");
			}
			$objSheet->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
				->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
			$objSheet->getStyle("{$cell}")->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
			$objSheet->getStyle("{$cell}")->getAlignment()->setWrapText(false);
			$column++;
		}
		$row_number++;
	}
	if ($return) {
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$filename = '/uploadfiles/export/'.generate_order_sn().'.xlsx';
		$objWriter->save(ROOT_PATH.$filename);
		return $filename;
	} else {
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="'.generate_order_sn().'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save('php://output');
		exit;
	}
}

//csv
function exportCommon($exportData, $headArr, $title)
{
    $total = count($exportData);
    header("Content-type:application/vnd.ms-excel;charset=UTF-8");
   // header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:filename=" . iconv("UTF-8", "GB18030", $title) . ".csv");
    $fp = fopen('php://output', 'a');
    fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM
    $headName = array_keys($headArr);
    $headValue = array_values($headArr);
    fputcsv($fp, $headValue);
    $size = 1000;
    $groupNum = ceil($total / $size);
    for ($i = 0; $i <= $groupNum; $i++) {
        $exportDataTemp = array_slice($exportData, $size * $i, $size);
        foreach ($exportDataTemp as $item) {
            $rows = array();
            foreach ($headName as $name) {
                $rows[] = $item[$name];
            }
            fputcsv($fp, $rows);
        }
        ob_flush();
        flush();
    }
}

//对象转数组
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}

//导入excel, $file对应根目录
function import_excel($file='', $sheet=0, $start_row=1, $delete_file=true) {
	$file = ROOT_PATH . $file;
	if (empty($file) || !file_exists($file)) die('EXCEL FILE NOT EXISTS');
	setlocale(LC_ALL, 'zh_CN');
	$objRead = new PHPExcel_Reader_Excel2007(); //建立reader对象
	if (!$objRead->canRead($file)) {
		$objRead = new PHPExcel_Reader_Excel5();
		if (!$objRead->canRead($file)) die('NOT EXCEL FILE');
	}
	require_once(FRAMEWORK_PATH . '/class/PHPExcel_1.8.0/Classes/PHPExcel/Shared/Date.php');
	$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
		'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
	$obj = $objRead->load($file); //建立excel对象
	$currSheet = $obj->getSheet($sheet); //获取指定的sheet表
	$columnH = $currSheet->getHighestColumn(); //取得最大的列号
	$columnCnt = array_search($columnH, $cellName);
	$rowCnt = $currSheet->getHighestRow(); //获取总行数
	$data = array();
	for ($row=$start_row; $row<=$rowCnt; $row++) { //读取内容
		$cellValues = array();
		for ($column=0; $column<=$columnCnt; $column++) {
			$cellId = $cellName[$column].$row;
			$cell = $currSheet->getCell($cellId);
			if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_NUMERIC) {
				$cellValue = $cell->getValue();
				$cellstyleformat = $cell->getStyle()->getNumberFormat();
				$formatcode = $cellstyleformat->getFormatCode();
				if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $formatcode)) {
					$cellValue = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($cellValue));
				} else {
					//$cellValue = PHPExcel_Style_NumberFormat::toFormattedString($cellValue, $formatcode);
					$cellValue = $cell->getFormattedValue();
				}
			} else {
				//$cellValue = $cell->getCalculatedValue(); //获取公式计算的值
				$cellValue = $cell->getFormattedValue();
			}
			if ($cellValue instanceof PHPExcel_RichText) $cellValue = $cellValue->__toString(); //富文本转换字符串
			$cellValues[$cellName[$column]] = $cellValue;
		}
		$notEmptyCell = false;
		foreach ($cellValues as $k=>$g) {
			if (!empty($g) && strlen(trim(strval($g)))) {
				$notEmptyCell = true;
				break;
			}
		}
		if ($notEmptyCell) {
			foreach ($cellValues as $k=>$g) {
				$data[$row][$k] = $g;
				//$data[$row][$k] = iconv('gb2312', 'utf-8//IGNORE', $g);
			}
		}
	}
	if ($delete_file) unlink($file);
	return $data;
}

//导出文件或文件夹为zip
function export_zip($fileOrDir, $base_path='', $filename='') {
	$fileOrDir = ROOT_PATH.str_replace(ROOT_PATH, '', $fileOrDir);
	$add2zip = function($path, $zip, $base_path='') use(&$add2zip) {
		if (is_dir($path)) {
			$handler = opendir($path);
			while (($file = readdir($handler))!==false) {
				if ($file!='.' && $file!='..') {
					if (is_dir($path.'/'.$file)) {
						$add2zip($path.'/'.$file, $zip, $base_path);
					} else {
						$dir_path = explode('/'.$base_path, $path);
						$zip->addFile($path.'/'.$file, (strlen($dir_path[1])?$dir_path[1].'/':'').$file);
					}
				}
			}
			closedir($handler);
		} else {
			$filename = substr($path, strrpos($path, '/')+1);
			$zip->addFile($path, $filename);
		}
	};
	if (!strlen($filename)) $filename = generate_order_sn();
	$file = ROOT_PATH.UPLOAD_PATH."/{$filename}.zip";
	$zip = new ZipArchive();
	$res = $zip->open($file, ZipArchive::OVERWRITE);
	if ($res === TRUE) {
		$add2zip($fileOrDir, $zip, $base_path);
	}
	$zip->close();
	header('Content-Type: application/zip');
	header('Content-Transfer-Encoding: Binary');
	header('Content-Length: '.filesize($file));
	header('Content-Disposition: attachment; filename="'.basename($file).'"');
	readfile($file);
	unlink($file);
	exit;
}

//获取ip地址
function ip() {
	$ip = '';
	if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP']!='unknown') {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']!='unknown') {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	if ($ip=='' || $ip=='::1' || $ip=='127.0.0.1') {
		return '127.0.0.1';
	}
	return $ip;
}

//循环创建目录
function makedir($absolute_path, $mode = 0777) {
	if (is_dir($absolute_path)) return true;
	$root_path      = ROOT_PATH;
	$relative_path  = str_replace($root_path, '', $absolute_path);
	$each_path      = explode('/', $relative_path);
	$cur_path       = $root_path; //当前循环处理的路径
	foreach ($each_path as $path) {
		if ($path) {
			$cur_path = $cur_path . '/' . $path;
			if (!is_dir($cur_path)) {
				if (@mkdir($cur_path, $mode)) {
					@fclose(@fopen($cur_path . '/index.htm', 'w'));
				} else {
					return false;
				}
			}
		}
	}
	return true;
}

//截断过长的字符
function cut_str($sourcestr, $cutlength) {
	$returnstr = '';
	$i = 0;
	$n = 0;
	$str_length = strlen($sourcestr); //字符串的字节数
	while (($n<$cutlength) && ($i<=$str_length)) {
		$temp_str = substr($sourcestr, $i, 1);
		$ascnum = Ord($temp_str); //得到字符串中第$i位字符的ascii码
		if ($ascnum>=224) { //如果ASCII位高与224，
			$returnstr = $returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
			$i = $i+3; //实际Byte计为3
			$n++; //字串长度计1
		} else if ($ascnum>=192){ //如果ASCII位高与192，
			$returnstr = $returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i = $i+2; //实际Byte计为2
			$n++; //字串长度计1
		} else if ($ascnum>=65 && $ascnum<=90) { //如果是大写字母，
			$returnstr = $returnstr.substr($sourcestr,$i,1);
			$i=$i+1; //实际的Byte数仍计1个
			$n++; //但考虑整体美观，大写字母计成一个高位字符
		} else { //其他情况下，包括小写字母和半角标点符号，
			$returnstr = $returnstr.substr($sourcestr,$i,1);
			$i = $i+1; //实际的Byte数计1个
			$n = $n+0.5; //小写字母和半角标点等与半个高位字符宽...
		}
	}
	if ($str_length>$cutlength) {
		$returnstr = $returnstr; // "...";超过长度时在尾处加上省略号
	}
	return $returnstr;
}

//获取月份中文名称
function convert_chinese_month($month) {
	$arr = array("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月");
	return $arr[$month-1];
}

//将时间转换成刚刚、分钟、小时前
function get_time_word($date) {
	$curr = time();
	//$date = strtotime($date);
	$tmp = $curr - $date;
	if ($tmp < 60) {
		$word = '刚刚';
	} else if ($tmp < 3600) {
		$word = floor($tmp/60).'分钟前';
	} else if ($tmp < 86400) {
		$word = floor($tmp/3600).'小时前';
	} else if ($tmp < 259200) {//3天内
		$word = floor($tmp/86400).'天前';
	} else {
		$word = date('n月j日',$date);
	}
	return $word;
}

//两个日期之间的天数
function get_date_diff($date1, $date2) {
	if (strtotime($date1)>strtotime($date2)) list($date1, $date2) = array($date2, $date1);
	$start = strtotime($date1);
	$stop = strtotime($date2);
	$days = ($stop-$start)/86400;
	$result = array('days'=>$days, 'year'=>0, 'month'=>0, 'day'=>0, 'week'=>0);
	if ($days<7) { //如果小于7天直接返回天数
		$result['day'] = $days;
	} else if($days<=31) { //小于28天则返回周数，由于闰年2月满足了
		if ($stop==strtotime($date1.'+1 month')) {
			$result['month'] = 1;
		} else {
			$w = floor($days/7);
			$d = ($stop-strtotime($date1.'+'.$w.' week'))/86400;
			$result['week'] = $w;
			$result['day'] = $d;
		}
	} else {
		$w = 0;
		$y = floor($days/365);
		if ($y>=1) { //如果超过一年
			$start = strtotime($date1.'+'.$y.'year');
			$date1 = date('Y-m-d', $start);
			//判断是否真的已经有了一年了，如果没有的话就开减
			if ($start>$stop) {
				$date1 = date('Y-m-d',strtotime($date1.'-1 month'));
				$m = 11;
				$y--;
			}
			$days = ($stop-strtotime($date1))/86400;
		}
		if (isset($m)) {
			$w = floor($days/7);
			$d = $days-$w*7;
		} else {
			$m = isset($m) ? $m : round($days/30);
			$stop>=strtotime($date1.'+'.$m.'month') ? $m : $m--;
			if ($stop>=strtotime($date1.'+'.$m.'month')) {
				$d = $w = ($stop-strtotime($date1.'+'.$m.'month'))/86400;
				$w = floor($w/7);
				$d = $d-$w*7;
			}
		}
		$result['year'] = $y;
		$result['month'] = $m;
		$result['week'] = $w;
		$result['day'] = isset($d) ? $d : 0;
	}
	return $result;
}

//将从数据库查出的记录集的时间转换成更简短可读的时间格式，如刚刚、n分钟前
function convert_time_word($obj, $fields=array()) {
	if ($obj && is_array($obj) && $fields) {
		if (!is_array($fields)) $fields = array($fields);
		foreach ($obj as $k=>$g) {
			if (is_array($g)) {
				foreach ($fields as $field) {
					if (isset($g[$field])) $obj[$k][$field] = get_time_word($g[$field]);
				}
			} else {
				foreach ($fields as $field) {
					if (isset($g->$field)) $obj[$k]->$field = get_time_word($g->$field);
				}
			}
		}
	}
	return $obj;
}

//将从数据库查出的记录集的时间转换成可读的时间格式
function convert_time($obj, $fields=array(), $format='Y-m-d H:i:s') {
	if ($obj && is_array($obj) && $fields) {
		if (!is_array($fields)) $fields = array($fields);
		foreach ($obj as $k=>$g) {
			if (is_array($g)) {
				foreach ($fields as $field) {
					if (isset($g[$field])) $obj[$k][$field] = date($format, $g[$field]);
				}
			} else {
				foreach ($fields as $field) {
					if (isset($g->$field)) $obj[$k]->$field = date($format, $g->$field);
				}
			}
		}
	}
	return $obj;
}

//将手机号码中间设为星号
function get_mark_mobile($mobile) {
	if (preg_match("/^1[34578]\d{9}$/", $mobile)) {
		$mobile = substr_replace($mobile, '*****', 3, -3);
	}
	return $mobile;
}

//生成又拍云缩略图url
function get_upyun_thumb_url($url, $size="") {
	//if ($url && $size) {
	if ($url && $size && !is_my_domain($url)) {
		//产品缩略图
		if (strpos($url, "uploadfiles/") !== false) {
			$url = $url . "!" . $size;
		}
	}
	return $url;
}

//是否本站域名
function is_my_domain($url) {
	global $domain;
	if (strpos($url, $domain) !== false) {
		return true;
	} else {
		return false;
	}
}

//返回http协议
function https(){
    $is_https = false;
    if (!isset($_SERVER['HTTPS'])) return 'http://';
    if ($_SERVER['HTTPS']===1) { //Apache
        $is_https = true;
    } else if (strtoupper($_SERVER['HTTPS'])==='ON') { //IIS
        $is_https = true;
    } else if ($_SERVER['SERVER_PORT']==443) { //Other
        $is_https = true;
    }
    return $is_https ? 'https://' : 'http://';
}

//判断字符串包含中英文, 返回0全英文, 1全中文, 2中英混合
function is_en_cn($str) {
	$allen = preg_match("/^[a-zA-Z]+$/", $str); //判断是否是英文
	$allcn = preg_match("/^[\x7f-\xff]+$/", $str); //判断是否是中文
	if ($allen) {
		return 0;
	} else {
		if ($allcn) {
			return 1;
		} else {
			return 2;
		}
	}
}

//格式化URL
//by willson 2015/9/6 处理头像等缩略图的问题
function add_domain($url, $is_avatar=false) {
	global $domain;
	if ($url && strpos($url, "http://")===false && strpos($url, "https://")===false) {
		if (substr($url,0,2) == "//") {
			$url = "http:{$url}";
		} else if (substr($url,0,1) == "/") {
			$url = $domain.$url;
		} else {
			$url = $domain."/".$url;
		}
	}
	if ($url && $is_avatar && strpos($url, "/images/")===false && strpos($url, "!logo")===false) {
		$url .= "!logo";
	}
    return $url;
}

//递归一个数组/对象的属性加上域名
function add_domain_deep($obj, $fields=array()) {
	if (is_object($obj) || is_array($obj)) {
		foreach ($obj as $key => $val) {
			if (is_object($val) || is_array($val)) {
				if (is_object($obj)) {
					$obj->$key = add_domain_deep($val, $fields);
				} else if (is_array($obj)) {
					$obj[$key] = add_domain_deep($val, $fields);
				}
			} else {
				if (in_array($key, $fields)) {
					if (is_object($obj)) {
						$obj->$key = add_domain($val, is_avatar($key));
					} else if (is_array($obj)) {
						$obj[$key] = add_domain($val, is_avatar($key));
					}
				}
			}
		}
	} else {
		$obj = add_domain($obj);
	}
	return $obj;
}

//字符串是否包含avatar字样, 且判断是否本地图片(本地需要返回false,否则会按照又拍云规则增加后缀)
function is_avatar($str) {
	global $domain;
	if ($str) {
		if (strpos($str, "avatar")!==false) {
			if (strpos($str, $domain)!==false || (strpos($str, "http://")===false && strpos($str, "https://")===false)) {
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function addslashes_deep_obj($obj) {
	if (is_object($obj)) {
		foreach ($obj as $key => $val) {
			if (($val) == true) {
				$obj->$key = addslashes_deep_obj($val);
			} else {
				$obj->$key = addslashes_deep($val);
			}
		}
	} else {
		$obj = addslashes_deep($obj);
	}
	return $obj;
}

//转义
function addslashes_deep($value) {
	if (empty($value)) {
		return $value;
	} else {
		return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
	}
}

//解码经escape编码的字符串
function unescape($str, $charset='utf8') {
	if ($str=='') return '';
	if ($charset=='utf8') {
		$ret = '';
		$len = strlen($str);
		for ($i=0; $i<$len; $i++) {
			if ($str[$i]=='%' && $str[$i+1]=='u') {
				$val = hexdec(substr($str, $i+2, 4));
				if ($val<0x7f)$ret .= chr($val);
				else if ($val<0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
				else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
				$i += 5;
			} else if ($str[$i]=='%') {
				$ret .= urldecode(substr($str, $i, 3));
				$i += 2;
			} else $ret .= $str[$i];
		}
		return $ret;
	} else {
		$str = rawurldecode($str);
		preg_match_all("/%u.{4}|&#x.{4};|&#d+;|.+/U",$str,$r);
		$ar = $r[0];
		foreach ($ar as $k=>$v) {
			if (function_exists('mb_convert_encoding')) {
				if (substr($v,0,2)=='%u') $ar[$k] = mb_convert_encoding(pack("H4",substr($v,-4)),"GB2312","UCS-2");
				else if (substr($v,0,3)=='&#x') $ar[$k] = mb_convert_encoding(pack("H4",substr($v,3,-1)),"GB2312","UCS-2");
				else if (substr($v,0,2)=='&#') $ar[$k] = mb_convert_encoding(pack("H4",substr($v,2,-1)),"GB2312","UCS-2");
			} else {
				if (substr($v,0,2)=='%u') $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4)));
				else if (substr($v,0,3)=='&#x') $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,3,-1)));
				else if (substr($v,0,2)=='&#') $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,2,-1)));
			}
		}
		return join('', $ar);
	}
}

//判断手机登录还是电脑登录
function CheckSubstrs($substrs,$text){
    foreach($substrs as $substr)
        if(false!==strpos($text,$substr)){
            return true;
        }
    return false;
}

function isMobile(){
    $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';

    $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
    $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');

    $found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||
        CheckSubstrs($mobile_token_list,$useragent);

    if ($found_mobile){
        return true;
    }else{
        return false;
    }
}

//生成随机字母、数字
function random_str($length=4) {
	//生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
	$arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
	$str = '';
	$arr_len = count($arr);
	for ($i = 0; $i < $length; $i++) {
		$rand = mt_rand(0, $arr_len-1);
		$str .= $arr[$rand];
	}
	return $str;
}

//发送短信
function send_sms($mobile, $content, $template_id=0, $code=0) {
	global $sms_api_key, $sms_accountSid;
	if (strlen($sms_api_key)) {
        return send_sms_luosimao($mobile, $content, $template_id, $code);
	} else if (strlen($sms_accountSid)) {
		return send_sms_yuntongxun($mobile, $content, $template_id);
	} else {
		write_log('SMS LOST API KEY', '/temp/smslog.txt');
		return false;
	}
}

//螺丝帽
function send_sms_luosimao($mobile, $content, $template_id=0, $code=0) {
	if (API_DEBUG) return;
	global $sms_max_ip_time, $sms_api_key, $sms_sign;
	//if (!maxip($sms_max_ip_time)) return;
	include_once (FRAMEWORK_PATH."/class/sms/luosimao/luosimao.php");
	$sms = new luosimao(array('api_key'=>$sms_api_key, 'use_ssl'=>false));
	if (is_array($content)) $content = implode('', $content);
	if ($code == 1){
	    //验证码
        $content = "您的手机短信验证码是：".$content.",请不要告诉任何人。";
    }
	$content .= "【{$sms_sign}】";
	//发送接口，签名需在后台报备
	$res = $sms->send($mobile, $content);
	if ($res) {
		if (!isset($res['error'])) {
			write_log('FAILED, NO ERROR', '/temp/smslog.txt');
			return false;
		}
		if (intval($res['error'])!=0) {
			write_log('FAILED, CODE:'.$res['error'].', MSG:'.$sms->get_error($res['error']).' ('.$res['msg'].')', '/temp/smslog.txt');
			return false;
		}
		write_log("SMS SEND OK: {$mobile}=>{$content}", "/temp/smslog.txt");
		return true;
	} else {
		write_log('SMS SEND ERROR: '.serialize($sms->last_error()), '/temp/smslog.txt');
		return false;
	}
	//余额查询
	//$res = $sms->get_deposit();
}
//容联云通讯
function send_sms_yuntongxun($mobile, $content, $template_id=72071) {
	if (API_DEBUG) return;
	global $sms_max_ip_time, $sms_accountSid, $sms_accountToken, $sms_appId;
	if (!maxip($sms_max_ip_time)) return;
	include_once (FRAMEWORK_PATH."/class/sms/yuntongxun/CCPRestSmsSDK.php");
	//沙盒环境: sandboxapp.cloopen.com
	//生产环境: app.cloopen.com
	$serverIP = 'sandboxapp.cloopen.com';
	$serverPort = '8883'; //请求端口，生产环境和沙盒环境一致
	$softVersion = '2013-12-26'; //REST版本号，在官网文档REST介绍中获得
	$rest = new REST($serverIP, $serverPort, $softVersion);
	$rest->setAccount($sms_accountSid, $sms_accountToken);
	$rest->setAppId($sms_appId);
	$result = NULL;
	//发送模板短信
	if (is_array($content)) {
		$result = $rest->sendTemplateSMS($mobile, $content, $template_id);
	} else {
		if (strlen($content)) {
			$result = $rest->sendTemplateSMS($mobile, array($content), $template_id);
		}
	}
	if ($result == NULL ) {
		return false;
		//echo "result error!";
		//break;
	}
	if ($result->statusCode!=0) {
		return false;
		//echo "error code :" . $result->statusCode . "<br>";
		//echo "error msg :" . $result->statusMsg . "<br>";
		//TODO 添加错误处理逻辑
	} else {
		return true;
		//echo "Sendind TemplateSMS success!<br/>";
		// 获取返回信息
		//$smsmessage = $result->TemplateSMS;
		//echo "dateCreated:".$smsmessage->dateCreated."<br/>";
		//echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
	}
}

//指定时间限制ip操作, 默认60秒
function maxip($time=60) {
	$filename = ROOT_PATH.'/temp/maxip.txt';
	$ip = ip();
	$content = array();
	if (file_exists($filename)) {
		$data = file_get_contents($filename);
		if (strlen(trim($data))) {
			$content = unserialize(trim($data));
			if (!is_array($content)) $content = array();
			foreach ($content as $i=>$t) {
				if (intval($t)<time()-24*60*60) { //一天后删除
					unset($content[$i]);
				}
			}
			if (isset($content[$ip]) && intval($content[$ip])>time()-$time) return false;
		}
	}
	$content["{$ip}"] = time();
	$fp = fopen($filename, 'w');
	flock($fp, LOCK_EX);
	fwrite($fp, serialize($content));
	flock($fp, LOCK_UN);
	fclose($fp);
	return true;
}

//写log文件
function write_log($word='', $filename='/temp/log.txt') {
	if (substr($filename, 0, 1)!='/') $filename = '/'.$filename;
	@file_put_contents(ROOT_PATH.$filename, date('Y-m-d H:i:s')."\n".$word."\n", FILE_APPEND|LOCK_EX);
}

//防止 json_encode 后中文被转码
function json_encode_urlencode($obj) {
	if (!isset($obj)) return '';
	if (version_compare(PHP_VERSION, '5.4.0', '>=') && function_exists('create_function')) {
		$str = json_encode($obj);
		$str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches','return mb_convert_encoding(pack("H*",$matches[1]),"UTF-8","UCS-2BE");'), $str);
	} else {
		$str = urldecode(json_encode(url_encode($obj)));
	}
	return $str;
	//return str_replace(":null", ":\"\"", $str);
}

//将对象/数组进行urlencode
function url_encode($obj) {
	$o = deep_clone($obj);
	if (is_array($o)) {
		foreach ($o as $key=>$value) $o[urlencode($key)] = url_encode($value);
	} else if (is_object($o)) {
		foreach ($o as $name=>$value) $o->$name = url_encode($o->$name);
	} else if (is_string($o)) {
		$o = urlencode($o);
	}
	return $o;
}

//深度复制(防止PHP直接赋值到新变量后仍然指向同一内存指针)
function deep_clone($obj) {
	$o = '';
	if (is_array($obj)) {
		$o = array();
		foreach ($obj as $k=>$g) $o[$k] = unserialize(serialize($g));
	} else if (is_object($obj)) {
		$o = new stdClass();
		foreach ($obj as $name=>$g) $o->$name = unserialize(serialize($obj->$name));
	} else {
		$o = unserialize(serialize($obj));
	}
	return $o;
}

//批量unset, fields可为数组或空格分割的字符串
function unsets(&$obj, $fields) {
	if (is_string($fields)) $fields = explode(' ', $fields);
	if (is_array($obj)) {
		foreach ($fields as $field) {
			if (isset($obj[$field])) unset($obj[$field]);
			else {
				foreach ($obj as $k=>$g) unsets($obj[$k], $fields);
			}
		}
	} else if (is_object($obj)) {
		foreach ($fields as $field) {
			if (isset($obj->$field)) unset($obj->$field);
			else {
				foreach ($obj as $k=>$g) unsets($g, $fields);
			}
		}
	} else {
		unset($obj);
	}
}

//跳转网址后终止
function location($url) {
	if (substr(strtolower(trim($url)), 0, 9)=='location:') $url = substr(trim($url), 9);
	header("Location:{$url}");
	exit;
}

//原样输出
function debug($obj) {
	if (IS_API) {
		echo json_encode($obj);
	} else {
		print '<pre>';
		print_r($obj);
		print '</pre>';
	}
	exit;
}

//格式化价格
function format_price($price) {
	if (is_numeric($price)) {
		$price = number_format($price, 2);
	}
	return $price;
}

//图片转base64
function image_base64($file) {
	$base64 = '';
	$info = getimagesize($file);
	$data = fread(fopen($file, 'r'), filesize($file));
	return 'data:'.$info['mime'].';base64,'.base64_encode($data);
}

//数组转对象
function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }

    return (object)$arr;
}

//输出script
function script($msg='', $url='', $js='') {
	$html = '<meta charset="UTF-8"><script>';
	if ($msg) $html .= "alert('{$msg}');";
	if ($url) $html .= "location.href = '{$url}';";
	if ($js) $html .= $js;
	$html .= '</script>';
	exit($html);
}

//判断是否PJAX请求
function is_pjax() {
	return array_key_exists('HTTP_X_PJAX', $_SERVER) && $_SERVER['HTTP_X_PJAX'];
}

//POST方式提交数据
function postData($url, $params=array(), $isJson=false) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_POST, TRUE);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
	if (!empty($params)) {
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params); //如果params为数组即使用multipart/form-data提交, 为字符串即使用application/x-www-form-urlencoded
	}
	curl_setopt($ch, CURLOPT_URL, $url);
	if (substr($url, 0, 8)=='https://') {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //对认证证书来源的检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //从证书中检查SSL加密算法是否存在
	}
	$data = curl_exec($ch);
	if ($data === false) {
		echo 'Curl error: ' . curl_error($ch);
		exit;
	}
	curl_close($ch);
	if ($isJson) {
		$data = json_decode($data, true);
		if (is_null($data)) $data = '';
	}
	return $data;
}

//快递鸟 - 物流公司对应字母
//http://www.kdniao.com/YundanChaxunAPI.aspx
function kdniao() {
	return array(
		'EMS' => 'EMS快递',
		'SF' => '顺丰快递',
		'STO' => '申通快递',
		'YTO' => '圆通快递',
		'YD' => '韵达快递',
		'HTKY' => '汇通快递',
		'HHTT' => '天天快递',
		'ZTO' => '中通快递',
		'ZJS' => '宅急送快递',
		'YZPY' => '中国邮政',
		'QFKD' => '全峰快递',
		'GTO' => '国通快递',
		'FAST' => '快捷快递',
		'JD' => '京东快递',
		'LB' => '龙邦快递',
		'DBL' => '德邦物流',
		'RFD' => '如风达快递',
		'QRT' => '全日通快递',
		'JJKY' => '佳吉快运',
		'DHL' => 'DHL快递'
	);
}
function getkdniao($spellName, $mailNo) {
	if (!$spellName || !$mailNo) error('缺少快递单号或订单编号');
	$index = false;
	$kd = kdniao();
	preg_match("/[\x{4e00}-\x{9fa5}]+/u", $spellName, $matches);
	if (count($matches)) {
		$companyName = str_replace('快递','',str_replace('物流','',str_replace('快运','',str_replace('速递','',str_replace('速运','',$spellName)))));
		foreach ($kd as $k => $v) {
			if (strpos($v, $companyName)!==false) {
				$index = $k;
				break;
			}
		}
	} else if (isset($kd[$spellName])) {
		$index = $spellName;
	}
	if ($index === false) error("没有该物流公司代号: {$spellName}");
	$EBusinessID = "1256920"; //电商ID
	$AppKey = "e7bbede8-6d12-439f-9ebf-d835613b638f"; //电商加密私钥
	$requestData = "{\"OrderCode\":\"\", \"ShipperCode\":\"{$index}\", \"LogisticCode\":\"{$mailNo}\"}";
	$dataSign = "{$requestData}{$AppKey}";
	$dataSign = urlencode(base64_encode(md5($dataSign)));
	$postData = array(
		'EBusinessID' => $EBusinessID,
		'RequestType' => '1002',
		'RequestData' => urlencode($requestData),
		'DataType' => '2',
		'DataSign' => $dataSign
	);
	$json = postData('http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx', $postData, true, true);
	if (is_array($json)) {
		if (intval($json['Success'])==1) {
			//$json['State'] 2:在途中, 3:签收, 4:问题件
			$result = json_encode($json);
			$result = str_replace('"AcceptStation":', '"context":', $result);
			$result = str_replace('"AcceptTime":', '"time":', $result);
			$result = str_replace('"Traces":', '"data":', $result);
			$result = preg_replace("/<\/?a[^>]*?>/", '', $result);
			$json = json_decode($result, true);
			if (!is_null($json) && is_array($json['data'])) {
				$json['data'] = array_reverse($json['data']);
				return $json;
			} else {
				return getickd($spellName, $mailNo);
			}
		} else {
			error($json['Reason']);
		}
	} else {
		error('快递鸟接口发生异常');
	}
}

//爱查快递
//http://www.ickd.cn
function ickd() {
	return array(
		'ems' => 'EMS快递',
		'shunfeng' => '顺丰快递',
		'shentong' => '申通快递',
		'yuantong' => '圆通快递',
		'yunda' => '韵达快递',
		'huitong' => '汇通快递',
		'tiantian' => '天天快递',
		'zhongtong' => '中通快递',
		'zhaijisong' => '宅急送快递',
		'pingyou' => '中国邮政',
		'quanfeng' => '全峰快递',
		'guotong' => '国通快递',
		'kuaijie' => '快捷快递',
		'jingdong' => '京东快递',
		'ririshun' => '日日顺物流',
		'longbang' => '龙邦快递',
		'debang' => '德邦物流',
		'rufeng' => '如风达快递',
		'quanritong' => '全日通快递',
		'jiaji' => '佳吉快运',
		'dhl' => 'DHL快递'
	);
}
function getickd($spellName, $mailNo) {
	if (!$spellName || !$mailNo) error('缺少快递单号或订单编号');
	$index = false;
	$kd = ickd();
	preg_match("/[\x{4e00}-\x{9fa5}]+/u", $spellName, $matches);
	if (count($matches)) {
		$companyName = str_replace('快递','',str_replace('物流','',str_replace('快运','',str_replace('速递','',str_replace('速运','',$spellName)))));
		foreach ($kd as $k => $v) {
			if (strpos($v, $companyName)!==false) {
				$index = $k;
				break;
			}
		}
	} else if (isset($kd[$spellName])) {
		$index = $spellName;
	}
	if ($index === false) error("没有该物流公司代号: {$spellName}");
	$data = file_get_contents("http://biz.trace.ickd.cn/{$index}/{$mailNo}?callback=callback");
	if (strpos($data, '/**/callback&&callback(')!==false) {
		$result = str_replace('/**/callback&&callback(', '', $data);
		$result = preg_replace("/<span[^>]+?>/", '', $result);
		$result = str_replace('<\\/span>', '', $result);
		$result = preg_replace("/<\/?a[^>]*?>/", '', $result);
		$result = substr($result, 0, strlen($result)-1);
		$json = json_decode($result, true);
		if (!is_null($json)) {
			if (intval($json['errCode'])==0) {
				if (is_array($json['data'])) {
					$json['data'] = array_reverse($json['data']);
					return $json;
				} else {
					return getkd100($spellName, $mailNo);
				}
			} else {
				error($json['message']);
			}
		} else {
			exit($data);
		}
	} else {
		error('爱查快递接口发生异常');
	}
}

//快递100
//http://www.kuaidi100.com
function kd100() {
	return array(
		'ems' => 'EMS快递',
		'shunfeng' => '顺丰快递',
		'shentong' => '申通快递',
		'yuantong' => '圆通快递',
		'yunda' => '韵达快递',
		'huitongkuaidi' => '汇通快递',
		'tiantian' => '天天快递',
		'zhongtong' => '中通快递',
		'zhaijisong' => '宅急送快递',
		'youzhengguonei' => '中国邮政',
		'quanfengkuaidi' => '全峰快递',
		'guotongkuaidi' => '国通快递',
		'longbanwuliu' => '龙邦快递',
		'debangwuliu' => '德邦物流',
		'rufengda' => '如风达快递',
		'quanritongkuaidi' => '全日通快递',
		'jiajiwuliu' => '佳吉快运',
		'dhl' => 'DHL快递'
	);
}
function getkd100($spellName, $mailNo) {
	if (!$spellName || !$mailNo) error('缺少快递单号或订单编号');
	$index = false;
	$kd = kd100();
	preg_match("/[\x{4e00}-\x{9fa5}]+/u", $spellName, $matches);
	if (count($matches)) {
		$companyName = str_replace('快递','',str_replace('物流','',str_replace('快运','',str_replace('速递','',str_replace('速运','',$spellName)))));
		foreach ($kd as $k => $v) {
			if (strpos($v, $companyName)!==false) {
				$index = $k;
				break;
			}
		}
	} else if (isset($kd[$spellName])) {
		$index = $spellName;
	}
	if ($index === false) error("没有该物流公司代号: {$spellName}");
	$result = file_get_contents("http://www.kuaidi100.com/query?type={$index}&postid={$mailNo}");
	$result = preg_replace("/<\/?a[^>]*?>/", '', $result);
	$json = json_decode($result, true);
	if (is_array($json)) {
		if (intval($json['status'])==200 && is_array($json['data'])) {
			$json['data'] = array_reverse($json['data']);
			return $json;
		} else {
			error($json['message']);
		}
	} else {
		error('快递100接口发生异常');
	}
}

//获取表单数据 by @jsong 2016-6-26
//兼容普通提交、RSA提交
function getDatas() {
	global $tbp;
	if (RSA_POST && strtoupper($_SERVER['REQUEST_METHOD'])=='POST') {
		$data = file_get_contents("php://input");
		if (strlen($data)) {
			$_POST = array();
			if (strlen($data)>=684 && strpos($data, '&')===false && substr($data, strlen($data)-1)=='=') {
				$GLOBALS['isRSA'] = true;
				$rsa = new Rsa(FRAMEWORK_PATH . '/class/rsa/keys', "{$tbp}private", "{$tbp}public");
				$data = $rsa->privDecode($data);
			}
			$json = json_decode($data);
			if (is_null($json)) {
				$arr = explode('&', $data);
				foreach ($arr as $g) {
					$gs = explode('=', $g);
					if (count($gs)>1) $_POST[$gs[0]] = $gs[1];
				}
			} else {
				foreach ($json as $key => $val) $_POST[$key] = $val;
			}
		}
	}
	return $_POST;
}






//友好提示
function error_tip($tip='') {
	$html = '<!doctype html>
	<html style="font-size:100px;">
	<head>
	<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=0" />
	<meta name="format-detection" content="telephone=no" />
	<meta name="format-detection" content="email=no" />
	<meta name="format-detection" content="address=no" />
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<meta charset="UTF-8">
	<title>'.$tip.'</title>
	<script type="text/javascript" src="/js/jquery-3.2.1.min.js"></script>
	</head>
	<body style="background:#ebfaff;">
	<style>
	html, body{height:100%; margin:0; padding:0; position:relative; text-align:center; font-family:Arial; -webkit-font-smoothing:antialiased; font-smoothing:antialiased; -moz-osx-font-smoothing:grayscale;}
	.tip-view{position:absolute; left:0; top:50%; width:100%; height:2.04rem; margin-top:-1.4rem;}
	.tip-view i{display:block; margin:0 auto; width:1.5rem; height:1.5rem; background:url() no-repeat center center; background-size:cover;}
	.tip-view span{display:block; width:100%; height:0.34rem; line-height:0.34rem; font-size:0.18rem;}
	.tip-view font{display:block; width:100%; height:0.2rem; line-height:0.2rem; font-size:0.14rem; color:#ccc;}
	.tip-view strong{font-weight:normal;}
	</style>
	<div class="tip-view">
		<i></i>
		<span>'.$tip.'</span>
		<font>That will be return after at <strong>5</strong>s</font>
	</div>
	<script>
	var count = 5, timer = setInterval(function(){
		if(count<=0){
			clearInterval(timer);
			timer = null;
			$(".tip-view").parent().hasClass("bodyView") ? removeBodyView() : history.back();
			return;
		}
		count--;
		$(".tip-view strong").html(count);
	}, 1000);
	</script>
	</body>
	</html>';
	echo $html;
	exit;
}
